package com.adcc.loadsheet.monitor.controller;

import com.adcc.aoc.devLib.common.log.Log;
import com.adcc.loadsheet.monitor.entity.ServerLog;
import com.adcc.loadsheet.monitor.entity.User;
import com.adcc.loadsheet.monitor.service.MonitorService;
import com.adcc.loadsheet.monitor.service.RestartService;
import com.adcc.loadsheet.monitor.service.ServerLogService;
import com.adcc.loadsheet.monitor.util.Constant;
import com.adcc.loadsheet.monitor.util.SystemConfigFactory;
import com.adcc.loadsheet.monitor.vo.*;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 监控控制层
 */
@Controller
@RequestMapping(value = "/monitor", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class MonitorController {

    @Autowired
    private MonitorService monitorService;

    @Autowired
    private ServerLogService serverLogService;

    @Autowired
    private RestartService restartService;


    @Autowired
    private SystemConfigFactory systemConfigFactory;


    @RequestMapping(value = "/showStatus", method = RequestMethod.GET)
    @ResponseBody
    public ResultVO showStatus() {
        ResultVO vo = new ResultVO();
        try {
            MonitorServerVO monitorServer = monitorService.getMonitorServer();
            if (monitorServer != null) {
                vo.getData().put("monitorServer", monitorServer);
            }
        } catch (Exception ex) {
            Log.error(MonitorController.class, "showStatus() error", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason(String.format(Constant.ERROR_QUERY, "监控信息"));
        }
        return vo;
    }

    /**
     * 显示最新日志
     * [2024-06-20：张丽娟：修改日志显示条数，将日志显示条数按照时间段显示]
     *
     * @param count 单位：小时
     * @return
     */
    @RequestMapping(value = "/showLogs", method = RequestMethod.GET)
    @ResponseBody
    public ResultVO showLogs(int count) {
        ResultVO vo = new ResultVO();
        try {
            List<ServerLogVO> voList = Lists.newArrayList();
            List<ServerLog> list = serverLogService.showLog(count);
            if (list != null && list.size() > 0) {
                for (ServerLog log : list) {
                    voList.add(new ServerLogVO(log));
                }
            }
            vo.getData().put("logs", voList);
        } catch (Exception ex) {
            Log.error(MonitorController.class, "showLogs() error", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason(String.format(Constant.ERROR_QUERY, "最新系统日志"));
        }
        return vo;
    }

    /**
     * 获取告警弹框内容
     * [2024-6-01：张丽娟：增加声音和弹窗告警的功能，系统支持对指定告警项进行声音和弹窗告警忽略的功能]
     */
    @RequestMapping(value = "/getAlarmContents", method = RequestMethod.GET)
    @ResponseBody
    public ResultVO getAlarmContents() {
        ResultVO vo = new ResultVO();
        try {
            List<AlarmLogVO> alarmContentList = serverLogService.getAlarmContents();
            vo.getData().put("alarmContentList", alarmContentList);
        } catch (Exception ex) {
            Log.error(MonitorController.class, "getAlarmContents() error", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason(String.format(Constant.ERROR_QUERY, "告警弹框"));
        }
        return vo;
    }

    /**
     * 告警确认
     * [2024-6-01：张丽娟：增加声音和弹窗告警的功能，系统支持对指定告警项进行声音和弹窗告警忽略的功能]
     *
     * @return
     */
    @RequestMapping(value = "/alarmConfirm/{moduleName}", method = RequestMethod.POST)
    @ResponseBody
    public ResultVO alarmConfirm(@PathVariable("moduleName") String moduleName) {
        ResultVO vo = new ResultVO();
        try {
            serverLogService.alarmConfirm(moduleName);
        } catch (Exception ex) {
            Log.error(MonitorController.class, "alarmConfirm() error", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason(Constant.CONFIRM_ERROR);
        }
        return vo;
    }


    /**
     * [2024-6-25：杨家兴：增加服务重启功能]
     *
     * @param serverName 服务名
     * @return
     */
    @RequestMapping(value = "/restart/{serverName}", method = RequestMethod.POST)
    @ResponseBody
    public ResultVO restart(@PathVariable String serverName, HttpServletRequest request, HttpServletResponse response) {
        ResultVO vo = new ResultVO();
        try {
            //权限校验
            if (this.roleAuth(request)) {
                //权限校验成功，重启操作
                vo = restartService.serviceRestart(serverName);
                if(vo.getStatus().equals(ResultStatus.SUCCESS)){
                    //记录操作日志
                    Log.info(Constant.OPERATION_LOG, (String) vo.getData().get("englishreason"));
                }else{
                    //记录操作日志
                    Log.error(Constant.OPERATION_LOG, (String) vo.getData().get("englishreason"));
                }
            } else {
                //权限校验失败，响应头设置跳转页面
                this.ajaxRedirect(request, response);
            }
        } catch (Exception ex) {
            Log.error(MonitorController.class, "restart() error", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason(Constant.ERROR_RESTART);
        }
        return vo;
    }

    /**
     * 重启的权限校验，判断是否是普通用户，是否开启了普通用户禁止重启操作，role为1是普通用户，role为0是admin
     *
     * @return true验证通过，false验证失败
     */
    private boolean roleAuth(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            //这里的User是登陆时放入session的
            User user = (User) session.getAttribute("user");
            //session中有user且通过检验，则返回true，否则返回false
            if (user != null) {
                //判断是否有权限重启
                String roleDisable = (String) systemConfigFactory.getRoleDisable().get("roleDisable");
                if (user.getRole() == 1 && roleDisable.equals("false")) {
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            Log.error(MonitorController.class,"roleAuth() error " , e);
            return false;
        }
    }

    /**
     * 给响应设置重定向请求头及路径信息
     */
    public void ajaxRedirect(HttpServletRequest request, HttpServletResponse response) {
        //重定向标识加载响应头中
        response.setHeader("MYREDIRECT", "REDIRECT");
        //设置重定向的路径
        response.setHeader("CONTENTPATH", request.getContextPath() + "/index");
    }

}
